package com.onurokan.someone4me.photo.dao;

import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.onurokan.someone4me.photo.domain.Photo;
import com.onurokan.someone4me.role.domain.Authority;

@Repository
@Transactional
public class HibernatePhotoDao implements PhotoDao {

	private SessionFactory sessionFactory;

	@Autowired
	public HibernatePhotoDao(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	public void addPhoto(Photo photo) throws ConstraintViolationException {
		currentSession().save(photo);
	}

	public void savePhoto(Photo photo) {
		currentSession().update(photo);
	}

	public Photo loadPhotoById(Long id) {
		return (Photo) currentSession().get(Photo.class, id);
	}

	public Set<Photo> loadPhotosByUserId(Long id) {
		Criteria criteria = currentSession().createCriteria(Photo.class);
		criteria.add(Restrictions.eq("user_id", id));
		List list = criteria.list();
		if (list.isEmpty()) {
			return null;
		}
		return (Set<Photo>) list;
	}

	public void remove(Photo photo) {
		currentSession().delete(photo);
	}

}
